<?php

namespace common\models;

use Yii;
use yii\web\UrlManager;
use wbraganca\behaviors\NestedSetBehavior;
use wbraganca\behaviors\NestedSetQuery; 

/**
 * This is the model class for table "category".
 *
 * @property string $id
 * @property integer $root
 * @property string $lft
 * @property string $rgt
 * @property integer $level
 * @property string $name
 * @property string $description
 * @property integer $parents
 * @property string $image
 * @property string $created
 * @property integer $order
 * @property string $seo_title
 * @property string $seo_keywork
 * @property string $seo_description
 */
class Category extends \yii\db\ActiveRecord {

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'category_online';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
        [['root', 'lft', 'rgt', 'level', 'parents', 'order'], 'integer'],
        [['description', 'seo_description'], 'string'],
        [['created'], 'safe'],
        [['name'], 'required'],
        [['name', 'image', 'seo_title', 'seo_keywork'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
        'id' => 'ID',
        'root' => 'Root',
        'lft' => 'Lft',
        'rgt' => 'Rgt',
        'level' => 'Level',
        'name' => 'Danh mục',
        'description' => 'Description',
        'parents' => 'Danh mục cha',
        'image' => 'Image',
        'created' => 'Created',
        'order' => 'Số thứ tự',
        'seo_title' => 'Seo Title',
        'seo_keywork' => 'Seo Keywork',
        'seo_description' => 'Seo Description',
        ];
    }

    /**
     *
     * @return type 
     */
    public function behaviors() {
        return [
            /*'NestedSetBehavior' => [
                'class' => '\sammaye\extensions\NestedSetBehavior',
                'leftAttribute' => 'lft',
                'rightAttribute' => 'rgt',
                'levelAttribute' => 'level'
            ],*/
            'NestedSetBehavior' => [
                'class' => NestedSetBehavior::className()
            ]
            
        ];
    }
    
    /**
     * 
     * @return NestedSetQuery
     */
    public static function find()
    {
        return new NestedSetQuery(get_called_class());
    }
    
    /**
     * get list category
     */
    public static function getListCategory($parent,$stop = null){
        $result = array();
        self::loopNode($result, $parent, $stop,"");
        return $result;
    }
    
    /**
     *
     * @param type $result
     * @param type $parent
     * @param type $stop
     * @return type 
     */
    public static function loopNode(&$result,$parent,$stop,$prefix,$separ = " - -"){
        if($stop != null && $parent == $stop)
            return true;
        else{
            $category = self::findOne($parent);
            $result[$category->id] = $prefix." ".$category->name;
            foreach($category->children()->orderBy('order')->all() as $item){
                self::loopNode($result, $item->id, $stop,$prefix.$separ,$separ);
            }
        }
    }
    
    /**
     * 
     */
    public function getArrayIdChildrenCategory(){
        $return = array($this->id);
        $children = $this->descendants()->all();
        foreach($children as $item){
            $return[] = $item->id;
        }
        return $return;
    }
    
    /**
     * 
     */
    public function moveProductToRoot(){
           $arrayCategory = $this->getArrayIdChildrenCategory();
           $connection = Yii::$app->db;
           $command = $connection->createCommand('UPDATE  product SET category_id = :root  WHERE category_id in ('.implode(',', $arrayCategory).')');
           $command->bindValue(':root', \Yii::$app->params['RootCategory']);
           $command->execute();
    }
    
    /**
     * 
     * @return type
     */
    public function getUrl(){
        return Yii::$app->urlManager->createUrl(['category/index', 'id' => $this->id,'alias' => \Resize\Clear::getTitleUrl($this->name)]);
    }
    
    /**
     * 
     */
    public function getUrlRss(){
        return Yii::$app->urlManager->createAbsoluteUrl(['rss/category', 'id' => $this->id,'alias' => \Resize\Clear::getTitleUrl($this->name)]);
    }
    
    /**
     * 
     * @return type
     */
    public function getUrlStore($storeId,$storeName){
        return Yii::$app->urlManager->createUrl(['store/category', 'id' => $storeId,'alias' => \Resize\Clear::getTitleUrl($storeName),'category_id' => $this->id]);
    }
    
    /**
     * 
     */
    public function getParentLevel($level = 2){
        if($this->level == $level)
            return $this;
        $parent = $this->ancestors()->all();
        foreach ($parent as $child) {
            if ($child->level == $level) {
                return $child;
            }
        }
        return null;
    }
    
    /**
     * 
     */
    public function getProductHomePage($limit = 8,$sort = "view DESC"){
        $children = $this->getArrayIdChildrenCategory();
        $products = Product::find()->andWhere(['category_id' => $children])->andWhere(['type' => Product::TypeShow()])->limit($limit)->orderBy($sort)->all();
        return $products;
    }
    
    /**
     * 
     */
    public static function getCategoryLevel3($ids = array()){
        if(count($ids) > 0){
            $categories = self::find()->where(['level' => 3])->andWhere(['in','id',$ids])->all();
        }else{
            $categories = self::find()->where(['level' => 3])->all();
        }
        return $categories;
    }
    
    /**
     * 
     */
    public static function getListLastCatagory(){
        $return = [];
        $name = "";
        $category = Category::findOne(\Yii::$app->params['RootCategory']);
        $children = $category->children()->all();
        foreach ($children as $item){
            self::loopLast($item->id,$name,$return);
        }
        return $return;
    }
    
    /**
     * 
     * @param type $id
     * @param type $name
     * @param string $arrayLast
     */
    public static function loopLast($id,$name,&$arrayLast){
        $category = Category::findOne($id);
        $children = $category->children()->all();
        if(count($children) > 0){
            $name = $category->name." >> ";
            foreach($children as $item){
                self::loopLast($item->id,$name,$arrayLast);
            } 
        }else{
            $arrayLast[$category->id] = $name.$category->name;
        }
    }
    
    /**
     * 
     */
    public static function getListLastCatagoryObject(){
        $return = [];
        $name = "";
        $category = Category::findOne(\Yii::$app->params['RootCategory']);
        $children = $category->children()->all();
        foreach ($children as $item){
            self::loopLastObject($item->id,$name,$return);
        }
        return $return;
    }
    
    /**
     * 
     * @param type $id
     * @param type $name
     * @param string $arrayLast
     */
    public static function loopLastObject($id,$name,&$arrayLast){
        $category = Category::findOne($id);
        $children = $category->children()->all();
        if(count($children) > 0){
            $name = $category->name." >> ";
            foreach($children as $item){
                self::loopLastObject($item->id,$name,$arrayLast);
            } 
        }else{
            $arrayLast[] = [
                'id' => $category->id,
                'name' => $name.$category->name
            ];
        }
    }
    
    /**
     * 
     */
    public function getSeoTitle(){
        if(strlen($this->seo_title) > 0){
            return $this->seo_title;
        }else{
            return $this->name;
        }
    }
    
    /**
     * 
     */
    public function getSeoKeywords(){
        if(strlen($this->seo_keywork) > 0){
            return $this->seo_keywork;
        }else{
            return $this->name;
        }
    }
    
    /**
     * 
     */
    public function getSeoDescription(){
        if(strlen($this->seo_description) > 0){
            return $this->seo_description;
        }else{
            return $this->name;
        }
    }
    

}
